package com.zdkj.subway.support.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.annotation.Inner;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.support.dto.in.SwMessageDTO;
import com.zdkj.subway.support.entity.SwMessage;
import com.zdkj.subway.support.service.SwMessageService;
import com.zdkj.subway.support.util.RoleCheckUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;


/**
 * 站内消息
 *
 * @author cui_com
 * @date 2020-08-04 18:28:42
 */
@RestController
@AllArgsConstructor
@RequestMapping("/swmessage")
@Api(value = "swmessage", tags = "站内消息管理")
public class SwMessageController {

    private final SwMessageService swMessageService;

    private final Integer REVIEW = 1;

    private final Integer NO_REVIEW = 0;

    /**
     * 分页查询
     *
     * @param page      分页对象
     * @param swMessage 站内消息
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getSwMessagePage(Page page, SwMessage swMessage) {
        return R.ok(swMessageService.page(page, Wrappers.query(swMessage)));
    }


    @ApiOperation(value = "分页查询详细信息", notes = "分页查询详细信息")
    @GetMapping("/detail/page")
    public R getSwMessageDetailPage(Page page, SwMessage swMessage) {
        List<Integer> roles = SecurityUtils.getRoles();
        String title = swMessage.getTitle();
        String msgType = swMessage.getMsgType();
        Integer status = swMessage.getStatus();
        String searchType = swMessage.getSearchType();
        //swMessage.setTitle(null);
        QueryWrapper<SwMessage> QueryWrapper = new QueryWrapper<>();
        String dateCondition = swMessage.getCreateTimeDTO();
		String dateApplyCondition = swMessage.getApplyTimeDTO();
        if (StringUtils.isNotBlank(String.valueOf(status))) {
            QueryWrapper.eq("STATUS", status);
        }
        if (StringUtils.isEmpty(String.valueOf(searchType))) {
            if (StringUtils.isNotBlank(dateCondition)) {
                QueryWrapper.likeRight("CREATE_TIME", dateCondition);
            }
            if (StringUtils.isNotBlank(dateApplyCondition)) {
                QueryWrapper.likeRight("APPLY_TIME", dateApplyCondition);
            }
            if (StringUtils.isNotBlank(title)) {
                QueryWrapper.like("TITLE", title);
            }
            if (StringUtils.isNotBlank(msgType)) {
                QueryWrapper.eq("MSG_TYPE", msgType);
            }
        }
        QueryWrapper.orderByDesc("CREATE_TIME");
        if (!SecurityUtils.getUser().getBelongToLine()) {
            QueryWrapper.eq("line_code", SecurityUtils.getUser().getLineCode());
            QueryWrapper.eq("station_code", SecurityUtils.getUser().getStationCode());
            //普通车站用户 非站长
            if (!roles.contains(RoleCheckUtils.ZXFZZ_ROLE_CODE) && !roles.contains(RoleCheckUtils.ZXZZ_ROLE_CODE)) {
                QueryWrapper.isNull("ROLE_CODE");
            }
            if (roles.contains(RoleCheckUtils.ZXFZZ_ROLE_CODE)
                    || roles.contains(RoleCheckUtils.ZXZZ_ROLE_CODE)) {
                //中心站长
                QueryWrapper.in("ROLE_CODE", RoleCheckUtils.ZXZZ_ROLE_CODE); //发待办时 roleCode 写死 = 3
            }
            return R.ok(swMessageService.page(page, QueryWrapper));
        } else {
            //todo 写公用方法替换判断
            if (RoleCheckUtils.belongToLineContainsRoleCode(roles)) {
                QueryWrapper.in("ROLE_CODE", roles);
            } else {
                QueryWrapper.eq("dept_id", SecurityUtils.getUser().getDeptId());
                //QueryWrapper.isNull("ROLE_CODE");  线路人员，所有都按角色处理 20250310
                 QueryWrapper.eq("ROLE_CODE", roles);
            }
            return R.ok(swMessageService.page(page, QueryWrapper));
        }
    }

    /**
     * 通过id查询站内消息
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swMessageService.getById(id));
    }

    /**
     * 新增站内消息
     *
     * @param swMessage 站内消息
     * @return R
     */
    @ApiOperation(value = "新增站内消息", notes = "新增站内消息")
    @SysLog("新增站内消息")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('support_swmessage_add')")
    public R save(@RequestBody SwMessageDTO swMessage) {
        SwMessage defaultObj = ObjectUtils.getDefaultObj(SwMessage.class);
        BeanUtils.copyProperties(swMessage, defaultObj);
        return R.ok(swMessageService.save(defaultObj));
    }

    @PostMapping("/inner")
    @Inner
    public R saveInner(@RequestBody SwMessage swMessage) {
        swMessage.setStatus(NO_REVIEW);
        return R.ok(swMessageService.save(swMessage));
    }

    @PostMapping("/innerBatch")
    @Inner
    public R saveBatchInner(@RequestBody List<SwMessage> swMessage) {
        swMessage.stream().forEach(s -> s.setStatus(NO_REVIEW));
        return R.ok(swMessageService.saveBatch(swMessage));
    }

    /**
     * 修改站内消息
     *
     * @param swMessage 站内消息
     * @return R
     */
    @ApiOperation(value = "修改站内消息", notes = "修改站内消息")
    @SysLog("修改站内消息")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('support_swmessage_edit')")
    public R updateById(@RequestBody SwMessageDTO swMessage) {
        SwMessage obj = new SwMessage();
        BeanUtils.copyProperties(swMessage, obj);
        return R.ok(swMessageService.updateById(obj));
    }


    @ApiOperation(value = "批量审阅", notes = "批量审阅")
    @SysLog("批量审阅")
    @PutMapping("/review/batch")
    //@PreAuthorize("@pms.hasPermission('support_swmessage_update_batch')")
    public R updateBatchByIds(@RequestBody List<Integer> ids) {
        return R.ok(swMessageService.updateReviewByIds(ids));
    }

    @ApiOperation(value = "审阅", notes = "审阅")
    @SysLog("审阅")
    @PutMapping("/review/{id}")
    public R updateBatchById(@PathVariable Integer id) {
        return R.ok(swMessageService.updateReviewByIds(Arrays.asList(id)));
    }

    @ApiOperation(value = "撤回已阅", notes = "撤回已阅")
    @SysLog("撤回已阅")
    @PutMapping("/recallUnread/{id}")
    public R recallUnread(@PathVariable Integer id) {
        SwMessage swMessage = new SwMessage();
        swMessage.setId(id);
        swMessage.setStatus(NO_REVIEW);
        return R.ok(swMessageService.updateById(swMessage));
    }

    /**
     * 通过id删除站内消息
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除站内消息", notes = "通过id删除站内消息")
    @SysLog("通过id删除站内消息")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('support_swmessage_del')")
    public R removeById(@PathVariable Integer id) {
        return R.ok(swMessageService.removeById(id));
    }

}
